package com.hfb.mashibing.alip8.designpattern._01singleton;

import java.util.concurrent.TimeUnit;

/**
 * 线程安全的单利模式（经测试此写法在不同平台表现不一：在win上唯一，在mac上不唯一）
 *
 * 既不加锁，也可以实现线程安全的单利模式
 * @author HFB
 */
public class Mgr07 {

    private Mgr07(){System.out.println("singleton");}

    private static class Singleton{
        private static Singleton singleton = new Singleton();
    }

    public static Singleton getInstance() {
      return Singleton.singleton;
    }


    public static void main(String[] args) throws InterruptedException {
        Thread[] ts = new Thread[200];
        for (int i = 0; i < ts.length; i++) {
            ts[i] = new Thread(()->
                System.out.println(Mgr07.getInstance().hashCode())
            );
        }

        for (Thread t : ts) {
            TimeUnit.SECONDS.sleep(1);
            t.start();
        }
    }
}
